﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Xfrog.Net;

namespace Common
{
    public class DataApi
    {
        const string appkey = "b2572e2cb764b36fb56d64871c20cf95"; //流量接口appkey
        const string OpenID = "JHba0885a1fea7c824f7cf7aa9aa3f2794"; //流量接口appkey
        const string GetPhoneInfoKey = "4ac4c0aab1f8ac8fa01431e31590da27";


        /// <summary>
        /// 流量充值
        /// </summary>
        /// <param name="phone">手机号</param>
        /// <param name="pid">充值套餐ID</param>
        /// <param name="orderid">单号</param>
        public static void SendData(string phone, int pid, string orderid)
        {
            GetRequest2(phone, pid, orderid);
        }
        
        
        /// <summary>
        /// 查询联通 电信 移动 全部流量套餐列表
        /// </summary>
        /// <returns></returns>
        public static JsonObject GetFlowTable()
        {

            string url1 = "http://v.juhe.cn/flow/list";

            var parameters1 = new Dictionary<string, string>();

            parameters1.Add("key", appkey);//你申请的key

            string result1 = sendPost(url1, parameters1, "get");

            JsonObject newObj1 = new JsonObject(result1);
            String errorCode1 = newObj1["error_code"].Value;

            if (errorCode1 == "0")
            {
                Debug.WriteLine("成功");
            }
            else
            {
                //Debug.WriteLine("失败");
                Debug.WriteLine(newObj1["error_code"].Value + ":" + newObj1["reason"].Value);
            }
            return newObj1;
        }

        public static string getFlowTable_toStr()
        {

            string url1 = "http://v.juhe.cn/flow/list";

            var parameters1 = new Dictionary<string, string>();

            parameters1.Add("key", appkey);//你申请的key

            string result1 = sendPost(url1, parameters1, "get");

            JsonObject newObj1 = new JsonObject(result1);
            String errorCode1 = newObj1["error_code"].Value;

            if (errorCode1 == "0")
            {
                Debug.WriteLine("成功");
            }
            else
            {
                Debug.WriteLine(newObj1["error_code"].Value + ":" + newObj1["reason"].Value);
            }
            return newObj1.ToString();
        }

        public static string getFlowTable_Tostr()
        {

            string url1 = "http://v.juhe.cn/flow/list";

            var parameters1 = new Dictionary<string, string>();

            parameters1.Add("key", appkey);//你申请的key

            string result1 = sendPost(url1, parameters1, "get");

            JsonObject newObj1 = new JsonObject(result1);
            String errorCode1 = newObj1["error_code"].Value;

            if (errorCode1 == "0")
            {
                Debug.WriteLine("成功");
            }
            else
            {
                //Debug.WriteLine("失败");
                Debug.WriteLine(newObj1["error_code"].Value + ":" + newObj1["reason"].Value);
            }
            return newObj1.ToString();
        }

   
        #region 获取手机号归属地
        /// <summary>
        /// 获取手机号 运营商  归属地
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        public static string GetPhoneInfo(string phone)
        {
            string url1 = "http://apis.juhe.cn/mobile/get";

            var parameters1 = new Dictionary<string, string>();

            parameters1.Add("phone", phone);//你查询的电话号码
            parameters1.Add("key", GetPhoneInfoKey);//你申请的key
            parameters1.Add("dtype","json");
            string result1 = sendPost(url1, parameters1, "get");

            JsonObject newObj1 = new JsonObject(result1);
            String errorCode1 = newObj1["error_code"].Value;

            if (errorCode1 == "0")
            {
                Debug.WriteLine("成功");
            }
            else
            {
                //Debug.WriteLine("失败");
                Debug.WriteLine(newObj1["error_code"].Value + ":" + newObj1["reason"].Value);
            }
            return newObj1.ToString();
        }
  
        #endregion

        //3.提交流量充值
        public static string GetRequest2(string phone, int pid, string orderid)
        {
           
            string url3 = "http://v.juhe.cn/flow/recharge";
            
            var parameters3 = new Dictionary<string, string>();
         
            parameters3.Add("phone", phone); //需要充值流量的手机号码
            parameters3.Add("pid", pid.ToString()); //流量套餐ID
            parameters3.Add("orderid", orderid); //自定义订单号，8-32字母数字组合
            parameters3.Add("key",appkey);//你申请的key
            string sign = GetMD5(OpenID + appkey + phone + pid + orderid);//加密效验值
            parameters3.Add("sign", sign); //校验值，md5(OpenID+key+phone+pid+orderid)，结果转为小写

            string result3 = sendPost(url3, parameters3, "get");

            JsonObject newObj3 = new JsonObject(result3);
            String errorCode3 = newObj3["error_code"].Value;
            String reason=newObj3["reason"].Value;
            if (errorCode3 == "0")
            {
               return "true";
            }
            else
            {

                return reason;
            }


        }

     

        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="sDataIn"></param>
        /// <returns></returns>
        public static string GetMD5(string sDataIn)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] bytValue, bytHash;
            bytValue = System.Text.Encoding.UTF8.GetBytes(sDataIn);
            bytHash = md5.ComputeHash(bytValue);
            md5.Clear();
            string sTemp = "";
            for (int i = 0; i < bytHash.Length; i++)
            {
                sTemp += bytHash[i].ToString("X").PadLeft(2, '0');
            }
            return sTemp.ToLower();
        }

        /// <summary>
        /// Http (GET/POST)
        /// </summary>
        /// <param name="url">请求URL</param>
        /// <param name="parameters">请求参数</param>
        /// <param name="method">请求方法</param>
        /// <returns>响应内容</returns>
        static string sendPost(string url, IDictionary<string, string> parameters, string method)
        {
            if (method.ToLower() == "post")
            {
                HttpWebRequest req = null;
                HttpWebResponse rsp = null;
                System.IO.Stream reqStream = null;
                try
                {
                    req = (HttpWebRequest)WebRequest.Create(url);
                    req.Method = method;
                    req.KeepAlive = false;
                    req.ProtocolVersion = HttpVersion.Version10;
                    req.Timeout = 5000;
                    req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
                    byte[] postData = Encoding.UTF8.GetBytes(BuildQuery(parameters, "utf8"));
                    reqStream = req.GetRequestStream();
                    reqStream.Write(postData, 0, postData.Length);
                    rsp = (HttpWebResponse)req.GetResponse();
                    Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
                    return GetResponseAsString(rsp, encoding);
                }
                catch (Exception ex)
                {
                    return ex.Message;
                }
                finally
                {
                    if (reqStream != null) reqStream.Close();
                    if (rsp != null) rsp.Close();
                }
            }
            else
            {
                //创建请求
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + "?" + BuildQuery(parameters, "utf8"));

                //GET请求
                request.Method = "GET";
                request.ReadWriteTimeout = 5000;
                request.ContentType = "text/html;charset=UTF-8";
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));

                //返回内容
                string retString = myStreamReader.ReadToEnd();
                return retString;
            }
        }

        /// <summary>
        /// 组装普通文本请求参数。
        /// </summary>
        /// <param name="parameters">Key-Value形式请求参数字典</param>
        /// <returns>URL编码后的请求数据</returns>
        static string BuildQuery(IDictionary<string, string> parameters, string encode)
        {
            StringBuilder postData = new StringBuilder();
            bool hasParam = false;
            IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
            while (dem.MoveNext())
            {
                string name = dem.Current.Key;
                string value = dem.Current.Value;
                // 忽略参数名或参数值为空的参数
                if (!string.IsNullOrEmpty(name))//&& !string.IsNullOrEmpty(value)
                {
                    if (hasParam)
                    {
                        postData.Append("&");
                    }
                    postData.Append(name);
                    postData.Append("=");
                    if (encode == "gb2312")
                    {
                        postData.Append(HttpUtility.UrlEncode(value, Encoding.GetEncoding("gb2312")));
                    }
                    else if (encode == "utf8")
                    {
                        postData.Append(HttpUtility.UrlEncode(value, Encoding.UTF8));
                    }
                    else
                    {
                        postData.Append(value);
                    }
                    hasParam = true;
                }
            }
            return postData.ToString();
        }

        /// <summary>
        /// 把响应流转换为文本。
        /// </summary>
        /// <param name="rsp">响应流对象</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>响应文本</returns>
        static string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
        {
            System.IO.Stream stream = null;
            StreamReader reader = null;
            try
            {
                // 以字符流的方式读取HTTP响应
                stream = rsp.GetResponseStream();
                reader = new StreamReader(stream, encoding);
                return reader.ReadToEnd();
            }
            finally
            {
                // 释放资源
                if (reader != null) reader.Close();
                if (stream != null) stream.Close();
                if (rsp != null) rsp.Close();
            }
        }
    }
}
